// components/tab-switch/index.js
Component({
  properties: {
    tabs: {
      type: Array,
      value: []
    },
    currentIndex: {
      type: Number,
      value: 0
    }
  },
  data: {
    tagLeft: 0,
    preIndex: 0,
    nextIndex: 0,
    scrollWithAnimation: false
  },
  methods: {
    switchTab(e) {
      const context = this;
      const index = e.currentTarget.dataset.index;
      //存储索引前值
      this.setData({
        preIndex: this.data.currentIndex,
        scrollWithAnimation: true
      });
      //存储索引最新值
      this.setData({
        currentIndex: index
      });
      const query = wx.createSelectorQuery().in(this);
      // query.select('').boundingClientRect().exec(scrollRect => {

      // });
      query.selectAll('.tab-item').boundingClientRect().exec(function(rects){
        console.log(rects);
        let moveLeft = 0;
        let indexFuture = index;
        //若是前值大于当前值，则适当往前挪1或2
        if (context.data.preIndex > index) {
          let differ = index >= 2 ? 2 : 1;
          indexFuture -= differ;
          // console.log(indexFuture);
          if (indexFuture < 0) {
            indexFuture = 0;
          }
        }
        for (let i = 0; i < indexFuture; i++) {
          const element = rects[0][i];
          // console.log(element.width);
          moveLeft += element.width;
        }
        //设置scroll滚动距离
        context.setData({
          tagLeft: moveLeft
        });
      });
      //定义一个事件，供调用页面触发使用
      this.triggerEvent('change', { index });
      setTimeout(() => {
        this.setData({ scrollWithAnimation: false });
      }, 300);
      // setTimeout(() => {
        
      // }, 300);
    }
  }
});
